﻿Imports System.Activities
Imports System.Drawing
Imports System.ComponentModel
Imports System.Activities.Core.Presentation
Imports System.Activities.Presentation.Metadata

Public Class ReadKeyActivity
    Inherits AsyncCodeActivity
    Implements IRegisterMetadata

#Region "プロパティ"
    Public Property InputKey As OutArgument(Of String)
#End Region

    Private Delegate Function asyncReadKeyDelegate() As String

    Public Sub New()
        Me.DisplayName = GetResourceStrings("ActRKDisplayName", "コンソールキー入力")
    End Sub

    Protected Overrides Function BeginExecute(context As System.Activities.AsyncCodeActivityContext, callback As System.AsyncCallback, state As Object) As System.IAsyncResult
        Dim asyncExecute = New asyncReadKeyDelegate(AddressOf ExecuteReadKey)
        context.UserState = asyncExecute

        Return asyncExecute.BeginInvoke(callback, state)
    End Function

    Protected Overrides Sub EndExecute(context As System.Activities.AsyncCodeActivityContext, result As System.IAsyncResult)
        Dim asyncExecute = TryCast(context.UserState, asyncReadKeyDelegate)
        Dim copyResult = asyncExecute.EndInvoke(result)

        context.SetValue(Me.InputKey, copyResult)
    End Sub

    Private Function ExecuteReadKey() As String
        Dim result = Console.ReadKey(True).KeyChar
        Return result
    End Function

#Region "メタデータ"

    Public Sub Register() Implements System.Activities.Presentation.Metadata.IRegisterMetadata.Register
        Dim metadata As New DesignerMetadata
        metadata.Register()

        Dim builder As New AttributeTableBuilder
        builder.AddCustomAttributes(GetType(ReadKeyActivity),
                            New DesignerAttribute(GetType(ReadKeyActivityDesigner)),
                            New ToolboxBitmapAttribute("Images/Activity/console_readkey.png")
                            )
        builder.AddCustomAttributes(GetType(ReadKeyActivity), "InputKey",
                    New CategoryAttribute(GetResourceStrings("ACtRKPropertyCategory", "処理の設定")),
                    New DisplayNameAttribute(GetResourceStrings("ACtRKInputKeyProperty", "結果を受取る変数")),
                    New DescriptionAttribute(GetResourceStrings("ACtRKInputKeyDescription", "入力されたキーを受取る変数を設定します。")))

        MetadataStore.AddAttributeTable(builder.CreateTable)
    End Sub

#End Region

#Region "その他"

    ''' <summary>リソースより文字列の取得</summary>
    Private Shared Function GetResourceStrings(ByVal resourceName As String, ByVal defaultStrings As String)
        Dim locMes = CStr(Application.Current.TryFindResource(resourceName))
        If (locMes Is Nothing) OrElse (locMes.Trim = "") Then locMes = defaultStrings
        Return locMes
    End Function

#End Region

End Class
